package com.iwjw.ibatis.generate;


import com.iwjw.ibatis.generate.model.BuildRunnable;
import com.iwjw.ibatis.generate.model.CustomizeTableInfo;
import com.iwjw.ibatis.generate.model.GenerateConfig;
import com.iwjw.ibatis.generate.util.BuildTableInfoUtil;
import org.apache.commons.lang3.StringUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: huangweiwei
 * @email: ihuangweiwei@163.com
 * @created:2016/10/27
 */
public class AbstractGenerateTemplate {


    private String className = "com.mysql.jdbc.Driver";

    private String url;

    private String userName;

    private String password;

    private String modelPkg;

    private String mapperPkg;

    private String xmlPath;

    private List<CustomizeTableInfo> tableInfoList;

    private Connection connection;

    public AbstractGenerateTemplate(String url, String userName, String password) {
        this.url = url;
        this.userName = userName;
        this.password = password;
        try {
            Class.forName(className);
            connection = DriverManager.getConnection(url, userName, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void initPath(String modelPkg, String mapperPkg, String xmlPath) {
        GenerateConfig.MODEL_PKG = modelPkg;
        if (StringUtils.isEmpty(mapperPkg)) {
            GenerateConfig.MAPPER_BUILD = false;
        } else {
            GenerateConfig.MAPPER_PKG = mapperPkg;
        }
        if (StringUtils.isEmpty(xmlPath)) {
            GenerateConfig.XML_BUILD = false;
        } else {
            GenerateConfig.XML_PATH = xmlPath;
        }
    }


    public void setOptimisticKey(String optimisticKey) {
        GenerateConfig.OPTIMISTIC_KEY = optimisticKey;
    }


    /**
     * 对所有表映射
     */
    public void initAll() {
        List<String> tables = BuildTableInfoUtil.getTables(connection);
        initByTableNames(tables);
    }

    /**
     * 指定数据库表映射
     *
     * @param tableNames
     */
    public void initByTableNames(List<String> tableNames) {
        List<CustomizeTableInfo> customizeTableInfos = new ArrayList<CustomizeTableInfo>();

        for (String table : tableNames) {
            customizeTableInfos.add(new CustomizeTableInfo(table));
        }
        initByCustomizeTableInfos(customizeTableInfos);
    }


    /**
     * 定制修改，比如字段名和数据库字段名不同
     *
     * @param tableInfoList
     */
    public void initByCustomizeTableInfos(List<CustomizeTableInfo> tableInfoList) {
        for (CustomizeTableInfo table : tableInfoList) {
            BuildRunnable buildRunnable = new BuildRunnable(table.getTableName(), connection, table);
            buildRunnable.run();
        }
    }

}
